package map.graph;

import java.util.HashMap;
import java.util.LinkedList;

import com.taxi.server.carsearch.graph.Node;
import com.taxi.server.carsearch.graph.Way;

public class MapGraph implements MapGraphConstants {

	public double minlat;
	public double minlon;
	public double maxlat;
	public double maxlon;

	private HashMap<Integer, Node> nodes = new HashMap<Integer, Node>(300000);
	private LinkedList<Way> ways = new LinkedList<Way>();

	public MapGraph(double minlat, double minlon, double maxlat, double maxlon) {
		this.minlat = minlat;
		this.minlon = minlon;
		this.maxlat = maxlat;
		this.maxlon = maxlon;
	}

	public void addNode(Node n) {
		nodes.put(n.getId(), n);
	}

	public void addWay(Way w) {
		ways.add(w);
	}

	public HashMap<Integer, Node> getNodes() {
		return nodes;
	}

	public LinkedList<Way> getWays() {
		return ways;
	}

	public Node getNode(int id) {
		return nodes.get(id);
	}

	public Node getNearestNode(double lat, double lon) {
		Node nearest = null;
		double dist = -1;
		double cur_dist = 0;
		for (Node node : nodes.values()) {
			if (dist < 0) {
				nearest = node;
				dist = node.getDistance(lat, lon);
			} else {
				cur_dist = node.getDistance(lat, lon);
				if (cur_dist < dist) {
					dist = cur_dist;
					nearest = node;
				}
			}
		}

		return nearest;
	}

	public MapGraph subGraph(double minlat, double minlon, double maxlat,
			double maxlon) {
		MapGraph graph = new MapGraph(minlat, minlon, maxlat, maxlon);
		for (Node n : nodes.values()) {
			if (n.getLat() >= minlat - precision
					&& n.getLat() <= maxlat + precision
					&& n.getLon() >= minlon - precision
					&& n.getLon() <= maxlon + precision) {
				graph.addNode(n);
				for (Way w : n.getWays()) {
					graph.addWay(w);
					graph.addNode(w.getNode2());
					for (Way w2 : w.getNode2().getWays()) {
						graph.addWay(w2);
						graph.addNode(w.getNode2());
					}
				}
			}
		}

		return graph;
	}

}
